package com.mdd.usercenter.service.impl;

import cn.hutool.json.JSONUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.mdd.usercenter.contant.UserConstant;
import com.mdd.usercenter.mapper.UserMapper;
import com.mdd.usercenter.common.ErrorCode;
import com.mdd.usercenter.exception.BusinessException;
import com.mdd.usercenter.model.domain.User;
import com.mdd.usercenter.model.vo.UserVo;
import com.mdd.usercenter.service.UserService;
import com.mdd.usercenter.utils.AlgorithmUtils;
import javafx.util.Pair;
import lombok.extern.slf4j.Slf4j;
import net.bytebuddy.description.method.MethodDescription;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.util.DigestUtils;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.util.*;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import java.util.stream.Collectors;

/**
 * 用户服务实现类
 *
 * @author mdd
 */
@Service
@Slf4j
public class UserServiceImpl extends ServiceImpl<UserMapper, User>
        implements UserService{

    @Resource
    private UserMapper userMapper;

    @Autowired
    private RedisTemplate<String,Object> redisTemplate;

    /**
     * 盐值，混淆密码
     */
    private static final String SALT = "yupi";

    @Override
    public long userRegister(String userAccount, String userPassword, String checkPassword, String planetCode) {
        // 1. 校验
        if (StringUtils.isAnyBlank(userAccount, userPassword, checkPassword, planetCode)) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "参数为空");
        }
        if (userAccount.length() < 4) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "用户账号过短");
        }
        if (userPassword.length() < 8 || checkPassword.length() < 8) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "用户密码过短");
        }
        if (planetCode.length() > 5) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "星球编号过长");
        }
        // 账户不能包含特殊字符
        String validPattern = "[`~!@#$%^&*()+=|{}':;',\\\\[\\\\].<>/?~！@#￥%……&*（）——+|{}【】‘；：”“’。，、？]";
        Matcher matcher = Pattern.compile(validPattern).matcher(userAccount);
        if (matcher.find()) {
            return -1;
        }
        // 密码和校验密码相同
        if (!userPassword.equals(checkPassword)) {
            return -1;
        }
        // 账户不能重复
        QueryWrapper<User> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("userAccount", userAccount);
        long count = userMapper.selectCount(queryWrapper);
        if (count > 0) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "账号重复");
        }
        // 星球编号不能重复
        queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("planetCode", planetCode);
        count = userMapper.selectCount(queryWrapper);
        if (count > 0) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "编号重复");
        }
        // 2. 加密
        String encryptPassword = DigestUtils.md5DigestAsHex((SALT + userPassword).getBytes());
        // 3. 插入数据
        User user = new User();
        user.setUserAccount(userAccount);
        user.setUserPassword(encryptPassword);
        user.setPlanetCode(planetCode);
        boolean saveResult = this.save(user);
        if (!saveResult) {
            return -1;
        }
        return user.getId();
    }

    @Override
    public User userLogin(String userAccount, String userPassword, HttpServletRequest request) {
        // 1. 校验
        if (StringUtils.isAnyBlank(userAccount, userPassword)) {
            return null;
        }
        if (userAccount.length() < 4) {
            return null;
        }
        if (userPassword.length() < 8) {
            return null;
        }
        // 账户不能包含特殊字符
        String validPattern = "[`~!@#$%^&*()+=|{}':;',\\\\[\\\\].<>/?~！@#￥%……&*（）——+|{}【】‘；：”“’。，、？]";
        Matcher matcher = Pattern.compile(validPattern).matcher(userAccount);
        if (matcher.find()) {
            return null;
        }
        // 2. 加密
        String encryptPassword = DigestUtils.md5DigestAsHex((SALT + userPassword).getBytes());
        // 查询用户是否存在
        QueryWrapper<User> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("userAccount", userAccount);
        queryWrapper.eq("userPassword", encryptPassword);
        User user = userMapper.selectOne(queryWrapper);
        // 用户不存在
        if (user == null) {
            log.info("user login failed, userAccount cannot match userPassword");
            return null;
        }
        // 3. 用户脱敏
        User safetyUser = getSafetyUser(user);
        // 4. 记录用户的登录态
        request.getSession().setAttribute(UserConstant.USER_LOGIN_STATE, safetyUser);
        return safetyUser;
    }

    /**
     * 用户脱敏
     *
     * @param originUser
     * @return
     */
    @Override
    public User getSafetyUser(User originUser)  {
        if (originUser == null) {
            return null;
        }
        User safetyUser = new User();
        safetyUser.setId(originUser.getId());
        safetyUser.setUsername(originUser.getUsername());
        safetyUser.setUserAccount(originUser.getUserAccount());
        safetyUser.setAvatarUrl(originUser.getAvatarUrl());
        safetyUser.setGender(originUser.getGender());
        safetyUser.setPhone(originUser.getPhone());
        safetyUser.setEmail(originUser.getEmail());
        safetyUser.setPlanetCode(originUser.getPlanetCode());
        safetyUser.setUserRole(originUser.getUserRole());
        safetyUser.setUserStatus(originUser.getUserStatus());
        safetyUser.setCreateTime(originUser.getCreateTime());
        safetyUser.setTags(originUser.getTags());
        return safetyUser;
    }

    /**
     * 用户注销
     * @param request
     */
    @Override
    public int userLogout(HttpServletRequest request) {
        // 移除登录态
        request.getSession().removeAttribute(UserConstant.USER_LOGIN_STATE);
        return 1;
    }

    /**
     * 根据标签来搜素用户
     * @param tags
     * @return
     */
    @Override
    public List<User> searchUserByTags(List<String> tags) {
        //检验
        if (tags == null||tags.isEmpty()) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        //查询(通过mysql进行查询)
        /*LambdaQueryWrapper<User> queryWrapper = new LambdaQueryWrapper<>();
        for (String tag : tags) {
            queryWrapper.like(User::getTags,tag);
        }
        List<User> list = list(queryWrapper);*/
        //通过内存进行过滤。
        List<User> list = list();
        Gson gson = new Gson();
        List<User> collect = list.stream().filter(user -> {
            String tags1 = user.getTags();
            if (!StringUtils.isNotBlank(tags1)) {
                return false;
            }
            List<String> tagsName = gson.fromJson(tags1,new TypeToken<List<String>>() {
            }.getType());
            for (String tag : tags) {
                if (!tagsName.contains(tag)) {
                    return false;
                }
            }
            return true;
        }).collect(Collectors.toList());
        //用户脱敏
         ArrayList<User> users = new ArrayList<>();
        for (User user : collect) {
            users.add(getSafetyUser(user));
        }
        //返回数据
        return users;
    }

    /**
     * 更新用户信息
     * @param user
     * @return
     */
    @Override
    public Integer updateUser(User user, User loginUser) {
        //校验权限
        //管理员可以更新任意用户
        if (!isAdmin(loginUser)&&user.getId().longValue() != loginUser.getId().longValue()) {
            throw new BusinessException(ErrorCode.NO_AUTH);
        }
        //如果用户没有传任何要更新的值直接返回
        if (!checkUser(user)) {
            throw new BusinessException(ErrorCode.NULL_ERROR,"没有传入要修改的值");
        }
        Long id = user.getId();
        if (id == null) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        boolean res = updateById(user);
        return res? 1:0;
    }

    /**
     * 检查用户是否有更新的值
     * @param user
     * @return
     */
    boolean checkUser(User user){
        if (user.getUsername() == null && user.getAvatarUrl() == null && user.getGender() == null && user.getPhone() == null && user.getEmail() == null) {
            return false;
        }
        return true;
    }

    /**
     * 获取当前登录用户
     * @param session
     * @return
     */
    @Override
    public User getLoginUser(HttpSession session) {
        if (session == null) {
            return null;
        }
        //从session中获取当前登录用户信息
        User attribute = (User) session.getAttribute(UserConstant.USER_LOGIN_STATE);
        if (attribute==null){
            //无权限
            throw new BusinessException(ErrorCode.NO_AUTH);
        }
        return attribute;
    }

    /**
     * 匹配相识用户
     * @param num
     * @param loginUser
     * @return
     */
    @Override
    public List<UserVo> matchUsers(long num, User loginUser) {
        //1.获取所有用户
        //查询性能优化(只查询需要的字段,并且只查询标签不为空的数据)
        LambdaQueryWrapper<User> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.select(User::getId,User::getTags).notIn(User::getTags,"[]");
        List<User> users = list(queryWrapper );
        //2.获取相似度列表
        //2.1获取登录用户标签
        String tags = loginUser.getTags();
        //2.2转成标签列表
        Gson gson = new Gson();
        List<String> currentTagsList = gson.fromJson(tags, new TypeToken<List<String>>() {
        }.getType());
        //2.3进行匹配(使用pair用来封装user在users中的索引和与当前用户编辑距离)
        List<Pair<Integer,Integer>> indexDistanceList = new ArrayList<>();

        for (int i = 0; i < users.size(); i++) {
            String tags1 = users.get(i).getTags();
            //没有标签，或为当前用户自己
            if (tags1 == null || users.get(i).getId().equals(loginUser.getId())) {
                continue;
            }
            List<String> tagsList = gson.fromJson(tags1, new TypeToken<List<String>>() {
            }.getType());
            //进行匹配
            int distance = AlgorithmUtils.minDistance(currentTagsList, tagsList);
            //加入到相似度列表中
            indexDistanceList.add(new Pair<>(i,distance));
        }
        //按照编辑距离进行升序排序
        List<Pair<Integer, Integer>> sortList = indexDistanceList.stream().sorted((a, b) -> {
            return a.getValue() - b.getValue();
        }).collect(Collectors.toList());
        //取出前num条
        return sortList.stream().limit(num).map(pair-> {
            User user = users.get(pair.getKey());
            User byId = getById(user.getId());
            UserVo userVo = new UserVo();
            BeanUtils.copyProperties(byId,userVo);
            return userVo;
        }).collect(Collectors.toList());
    }


    /**
     * 是否为管理员
     *
     * @param request
     * @return
     */
    @Override
    public boolean isAdmin(HttpServletRequest request) {
        // 仅管理员可查询
        Object userObj = request.getSession().getAttribute(UserConstant.USER_LOGIN_STATE);
        User user = (User) userObj;
        return user != null && user.getUserRole() == UserConstant.ADMIN_ROLE;
    }

    public boolean isAdmin(User user) {
        return user != null && user.getUserRole() == UserConstant.ADMIN_ROLE;
    }



}




